/**
 * Notes: 路由控制器
 * Date: 2021-03-15 19:20:00 
 */

const BaseController = require('../controller/base_controller.js');
const appCode = require('../config/app_config.js').ROUTE_CODES;
const timeUtil = require('../../../framework/helpers/time_util.js');
const config = require('../../../config/config.js');
const util = require('../../../framework/helpers/util.js');
const dataCheck = require('../../../framework/helpers/data_check.js');
const cloudBase = require('../../../framework/cloud/cloud_base.js');
const router = require('../../../framework/cloud/router.js');
const detailRoute = require('./detail_route.js');

class RouteController extends BaseController {

	// 中间件
	async initSetup(mid) {

		if (!mid) mid = 'init';

		console.log(mid);

		// 取得开始时间
		const time = timeUtil.time();
		this._timestamp = time;

		if (config.TEST_MODE)
			console.log(this._request);

		// 赋值当前请求到控制器
		await this.initRequest();

		// 模块初始化
		switch (mid) {
			case 'init': { // 初始化，不判断token 
				break;
			}
			case 'check': { // 简单检测,不需要获取用户信息 
				if (!await this.isLogin()) {
					console.log('Failed to check');
					this.getFail('请登录后操作');
					return false;
				}
				break;
			}
			case 'get': { // 获取数据,获取用户信息 
				if (!await this.isLogin()) {
					console.log('Failed to get');
					this.getFail('请登录后操作');
					return false;
				}
				// 回填
				await this.initUser();
				break;
			}
			case 'one': { // 操作数据,获取用户信息,并且仅用户能操作
				if (!await this.isLogin()) {
					console.log('Failed to one');
					this.getFail('请登录后操作');
					return false;
				}
				// 回填
				await this.initUser();
				break;
			}
			case 'admin': { // 管理员操作,获取用户信息,并且仅管理员能操作
				if (!await this.isAdmin()) {
					console.log('Failed to admin');
					this.getFail('需管理员身份才能操作');
					return false;
				}
				// 回填
				await this.initUser();
				break;
			}
			case 'openapi': { // 下载 
				break;
			}
			default: {
				console.error('未定义的中间件');
				this.getFail('Invalid middleware:' + mid);
				return false;
			}
		}

		return true;
	}

	/** 主路由 */
	async main() {
		let _route = util.route(this._request.route, this._route_dev);
		let _action = this._request.action || 'mcloud';
		console.log('MAIN ROUTE', _route, _action);

		switch (_route) {
			case 'mcloud': {
				if (_action.startsWith('route_')) {
					// TODO处理路由
					let func = _action.replace('route_', '');
					let routeCode = this.getParameter('code', true);
					await this.runRoute(func, routeCode);
					return;
				}
				break;
			}
			case 'admin': {
				if (!await this.initSetup('admin')) return;
				await this.adminMain();
				return;
			}
			case 'wecom': {
				// 企业微信API路由
				let WecomController = require('./wecom/wecom_controller.js');
				let controller = new WecomController(this._request);
				await controller[_action]();
				this.setResult(controller.getResult());
				break;
			}
			case 'passport': {
				// 不要包含数据校验
				if (!await this.initSetup('init')) return;
				await this.passportMain();
				break;
			}
			case 'user': {
				if (!await this.initSetup('one')) return;
				await this.userMain();
				break;
			}
			default:
				if (detailRoute[_route]) {
					return await this.runRoute(_action, detailRoute[_route]);
				}
				else {
					this.getFail('错误的控制器方法, controller=' + _route);
				}
				return;
		}
	}

	// 路由处理
	async runRoute(action, routeCode) {
		if (!routeCode) {
			return this.getFail('路由编码[code]缺失');
		}

		// 路由解码
		let ctr = '';
		let size = (routeCode.length);
		let first = routeCode.indexOf('_');
		let last = routeCode.lastIndexOf('_');

		try {
			if (size <= 2 || first != 1 || last == 1 || last == 0) {
				// 默认模式 形如： 1_xxx
				let num = routeCode.split('_')[0] || '';
				routeCode = appCode[num];
				if (!routeCode) {
					console.error('Invalid routeCode.mode1= ', routeCode);
					return this.getFail('路由编码[code]错误');
				}
				ctr = require('./' + routeCode + '_controller.js');
			}
			else {
				// 精准指向 形如：A_meet_B
				let arr = routeCode.split('_');
				ctr = require('./' + arr[0] + '/' + arr[1] + '_controller.js');
			}

			// 路由入口
			await this.initRoute(action, ctr);
		} catch (ex) {
			console.error(ex);
			this.getFail('路由执行错误, ACTION=' + action + ' ' + ex);
		}
		return;
	}

	// 调用控制器方法
	async initRoute(method, ctr) {
		let controller;
		if (ctr.default) controller = new ctr.default(this._request);
		else controller = new ctr(this._request);

		if (!controller[method]) {
			this.getFail('方法[' + method + ']不存在');
			return;
		}

		await controller[method]();
		this.setResult(controller.getResult());
	}
}

// 集中路由
router.setRouter(RouteController);

module.exports = {
	// 云函数入口
	main: router.cloud,
	// 网站入口
	router: router.web
}; 